# -*- coding: utf-8 -*-
import json

from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, JsonResponse

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from account.forms import LoginForm


def user_login(request):
    login_error = False
    next_to = request.GET.get("next", reverse("index"))
    if request.method == 'POST':
        form = LoginForm(request.POST)
        next_to = request.POST.get("next", reverse("index"))
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = auth.authenticate(username=username, password=password)
            if user is not None and user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect(next_to)
            else:
                login_error = True

    return render(request, 'account/login.html',
                  {'login_error': login_error, 'next': next_to})


# Use the login_required() decorator to ensure only those logged in can
# access the view.
@login_required
def user_logout(request):
    # Since we know the user is logged in, we can now just log them out.
    auth.logout(request)
    # 返回注销前页面
    # return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    return HttpResponseRedirect(reverse("index"))


@login_required
@csrf_exempt
def user_settings(request):
    user = request.user
    if request.method == "POST":
        profile = user.userprofile
        if profile.settings:
            settings = json.loads(profile.settings)
        else:
            settings = {}
        if request.POST.get("sidebar_collapse") == "true":
            settings['sidebar_collapse'] = "true"
        else:
            settings['sidebar_collapse'] = "false"
        profile.settings = json.dumps(settings)
        profile.save()

    ret = {
        "name": user.username,
        "nickname": user.userprofile.nickname,
        "signature": user.userprofile.signature,
        "settings": user.userprofile.settings
    }
    return JsonResponse(ret)
